import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { nanoid } from 'nanoid';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
}

interface Conversation {
  id: string;
  title: string;
  messages: Message[];
}

interface ChatStore {
  conversations: Conversation[];
  activeConversation: Conversation | null;
  addConversation: (title: string) => void;
  setActiveConversation: (conversation: Conversation) => void;
  addMessage: (conversationId: string, message: Omit<Message, 'id'>) => void;
}

export const useChatStore = create<ChatStore>()(
  persist(
    (set, get) => ({
      conversations: [],
      activeConversation: null,

      addConversation: (title) => {
        const newConversation: Conversation = {
          id: nanoid(),
          title,
          messages: [],
        };
        set((state) => ({
          conversations: [...state.conversations, newConversation],
          activeConversation: newConversation,
        }));
      },

      setActiveConversation: (conversation) => {
        set({ activeConversation: conversation });
      },

      addMessage: (conversationId, message) => {
        const newMessage = { ...message, id: nanoid() };
        set((state) => ({
          conversations: state.conversations.map((conv) =>
            conv.id === conversationId
              ? { ...conv, messages: [...conv.messages, newMessage] }
              : conv
          ),
          activeConversation: state.activeConversation?.id === conversationId
            ? { ...state.activeConversation, messages: [...state.activeConversation.messages, newMessage] }
            : state.activeConversation,
        }));
      },
    }),
    {
      name: 'chat-storage',
    }
  )
); 